package middleware

import (
	"fitness/pkg/constant"
	"fitness/pkg/tools"
	"github.com/gin-gonic/gin"

	"net/http"
	"strings"
	"time"
)

func Jwt(c *gin.Context) {
	token := c.GetHeader(constant.HeaderSignToken)
	if token == "" {
		token = c.Query(constant.HeaderSignToken)
	}
	if token != "" {
		token = strings.ReplaceAll(token, constant.HeaderSignTokenStr, "")
	}
	userinfo := tools.ParseToken(token)
	if userinfo == nil || userinfo[constant.UserName] == nil || userinfo["create_time"] == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 400,
			"msg":  "验证失败",
		})
		c.Abort()
		return
	}
	createTime := int64(userinfo["create_time"].(float64))
	var expire int64 = 24 * 60 * 60
	nowTime := time.Now().Unix()
	if (nowTime - createTime) >= expire {
		c.JSON(http.StatusOK, gin.H{
			"code": http.StatusUnauthorized,
			"msg":  "token失效",
		})
		c.Abort()
	}
	c.Set(constant.UserInfo, userinfo)
	f := userinfo[constant.UserType]
	c.Set(constant.UserType, f)
	c.Set(constant.UserId, uint64(userinfo[constant.UserId].(float64)))
	c.Set(constant.UserName, userinfo[constant.UserName])
	c.Set("role_id", userinfo["role_id"])
}
